import NotFound from "../views/Notfound";
import Login from "@/views/Login";
//useRoutes钩子可以根据路由表自动生成路由匹配规则
//Navigate内置组件，路由重定向组件，只要页面渲染Navigate就重新执行跳转
import { Routes, Route, useRoutes, Navigate } from "react-router-dom";
import { MyAppType } from "./type";
import disPoseArr from "./list";
import LayoutComponent from "@/layout/LayoutComponent";
import { lazy } from "react";
import WithLoading from "@/layout/WithLoading";
import RequireAuth from "@/layout/RequireAuth";

const DefaultPage = lazy(() => import("@/views/DefaultPage"));

//这里的element放成layout组件 里面放outlet出口即可
const router: Array<MyAppType> = [
  {
    path: "/",
    name: "/",
    element: <Navigate to="/defaultPage" />, //当访问到/时，跳转到home，这就是路由重定向，Navigate组件只要加载了就会重新跳转一次
  },

  {
    path: "/",
    name: "/",
    element: <LayoutComponent />,
    children: [
      {
        path: "/defaultPage",
        name: "DefaultPage",
        element: WithLoading(<DefaultPage />),
      },
      ...disPoseArr,
    ],
  },
  {
    path: "/login",
    name: "Login",
    element: <Login />,
  },
  {
    path: "*", //*表示匹配不到任何一个路由规则
    name: "*",
    element: <NotFound />,
  },
];

function RouterView() {
  return (
    <Routes>
      {router.map((item, index) => (
        <Route key={index} path={item.path} element={item.element}>
          {item.children &&
            item.children.map((item2, index2) => {
              return (
                <Route
                  key={index2}
                  path={item2.path}
                  element={<RequireAuth>{item2.element}</RequireAuth>}
                ></Route>
              );
            })}
          {/* 匹配子路由地址错误 */}
          {item.children && (
            <Route key={`${index}-notfound`} path="*" element={<NotFound />} />
          )}
        </Route>
      ))}
    </Routes>
  );
}

export default RouterView;
